package com.gongpingjialoan.activity.loans;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.VipBuycarBean;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.LoanUtil;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.view.LoanCarModelItemView;
import com.gongpingjialoan.view.ProgressView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static com.gongpingjialoan.R.id.province;

/**
 * 实名信息
 */
public class RealNameinformationActivity extends BaseActivity implements View.OnClickListener {
    private final int REQUEST_CITY_FRAGMENT = 1; //城市回调
    private ProgressView mProgressView;
    private TextView submitT, provinceT, cityT;
    private EditText nameEt, identity_card_noEt;

    private LoanCarModelItemView car_mode_layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_real_nameinformation);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanNameView);
        setTitle("实名信息");
        setRightImage(R.drawable.kefu_phone, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanNameService);
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000253500"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        submitT = (TextView) findViewById(R.id.submit);
        provinceT = (TextView) findViewById(province);
        cityT = (TextView) findViewById(R.id.city);
        nameEt = (EditText) findViewById(R.id.name);
        identity_card_noEt = (EditText) findViewById(R.id.identity_card_no);
        car_mode_layout = (LoanCarModelItemView) findViewById(R.id.car_mode_layout);

        provinceT.addTextChangedListener(new MyTextWatcher());
        cityT.addTextChangedListener(new MyTextWatcher());
        nameEt.addTextChangedListener(new MyTextWatcher(true));
        identity_card_noEt.addTextChangedListener(new MyTextWatcher());

        submitT.setOnClickListener(this);
        findViewById(R.id.city_layout).setOnClickListener(this);

        if (UserLocation.getInstance().isIslocation()) {
            cityT.setText(UserLocation.getInstance().getCity());
            provinceT.setText(UserLocation.getInstance().getProvice());
        }
        initProgress();

    }

    private void initProgress() {
        mProgressView = (ProgressView) findViewById(R.id.progressView);
        mProgressView.setStrokeWidth(30);
        mProgressView.setStartAngle(135);
        mProgressView.setMaxAngle(270);
        mProgressView.animProgress(0.2f);
    }

    private void submit() {
        showProgressDialog();
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanNameCommit);
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                hidenProgressDialog();
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mySelf, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    LoanUtil.toLoanData(json);
                    LoanUtil.goToPerfect(mySelf);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.perfect_evaluations);
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("step", "realNameAuthentification");
        netDataJson.addParam("province", provinceT.getText().toString());
        netDataJson.addParam("city", cityT.getText().toString());
        netDataJson.addParam("identity_card_no", identity_card_noEt.getText().toString());
        netDataJson.addParam("name", nameEt.getText().toString());
        netDataJson.request("put");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.NameApplyClick);
                submit();
                break;
            case R.id.city_layout:
                Intent intent = new Intent();
                intent.setClass(mySelf, CityActivity.class);
                startActivityForResult(intent, REQUEST_CITY_FRAGMENT);
                break;
            default:
                break;
        }
    }

    // 选择完车型后,调用这辆
    @Subscribe
    public void onEventMainThread(VipBuycarBean vipBuycarBean) {
        PointRecordManage.getInstance().addPoint(mySelf, Piont.NameChooseClick);
        car_mode_layout.onBrandSelceted(vipBuycarBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private class MyTextWatcher implements TextWatcher {
        private boolean limit = false;

        public MyTextWatcher(boolean limit) {
            this.limit = limit;
        }

        public MyTextWatcher() {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            isReady();
            if (limit) {
                String editable = nameEt.getText().toString();
                String str = stringFilter(editable.toString());
                if (!editable.equals(str)) {
                    nameEt.setText(str);
                    //设置新的光标所在位置
                    nameEt.setSelection(str.length());
                }
            }
        }
    }

    //监听所有数据填满 才可以点击提交
    public void isReady() {
        submitT.setBackgroundResource(R.color.text_grey_dark);
        submitT.setEnabled(false);

        if (TextUtils.isEmpty(provinceT.getText().toString())) {
            return;
        }
        if (TextUtils.isEmpty(cityT.getText().toString())) {
            return;
        }
        String name = nameEt.getText().toString();
        if (TextUtils.isEmpty(name)) {
            return;
        }
        String identity_card_no = identity_card_noEt.getText().toString();
        if (TextUtils.isEmpty(identity_card_no)) {
            return;
        }
        if (identity_card_no.length() != 18) {
            return;
        }
        submitT.setBackgroundResource(R.color.blue_3fbbff);
        submitT.setEnabled(true);
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、和汉字
        String regEx = "[^a-zA-Z\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    String str_city = b.getString("city", "");
                    String str_province = b.getString("province", "");
                    if (!TextUtils.isEmpty(str_city)) {
                        cityT.setText(str_city);
                    }
                    if (!TextUtils.isEmpty(str_province)) {
                        provinceT.setText(str_province);
                    }
                    break;
                default:
                    break;
            }
        }

    }


    @Override
    public void finish() {
        super.finish();
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanNameBack);
    }

}
